package cn.jishiyu11.xeqb.activity.personalCenterActivitys.settingpage

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import cn.jishiyu11.xeqb.R
import cn.jishiyu11.xeqb.R.id.*
import cn.jishiyu11.xeqb.activity.LogoActivity
import org.json.JSONObject
import java.io.IOException
import cn.jishiyu11.xeqb.base.BaseActivity
import cn.jishiyu11.xeqb.http.http.i.DataCallBack
import cn.jishiyu11.xeqb.http.http.i.httpbase.*
import cn.jishiyu11.xeqb.utils.*
import cn.jishiyu11.xeqb.utils.PublicClass.CountDownTimerUtils
import cn.jishiyu11.xeqb.webview.X5WebViewActivity
import com.umeng.analytics.MobclickAgent
import kotlinx.android.synthetic.main.act_set_up_password.*
import okhttp3.Request
import kotlin.collections.HashMap

/**
 * Created by jsy_zj on 2017/6/28.
 * 修改密码 + 注册
 */
class SetUpPasswordActivity : BaseActivity(), View.OnClickListener, DataCallBack {

    private var mCountDownTimerUtils: CountDownTimerUtils? = null

    private var name: String? = "0"
    private var passwordType = 0//0修改密码，1忘记密码
    private var registerToken = ""
    private var checkcodeToken = ""


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_set_up_password)
        name = intent.extras!!.getString("name")
        passwordType = intent.extras!!.getInt("type")

        findViewById()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.title_image -> finish()
            R.id.password_button_code -> {
                //验证码功能
                if (StringUtil.isNullOrEmpty(password_phone!!.text.toString())) {
                    this.showShortToast("您输入的手机号码不能为空")
                } else if (!StringUtil.isMobileNO(password_phone!!.text.toString())) {
                    this.showShortToast("您输入的手机号码不正确,请重新输入")
                    password_phone!!.setText("")
                } else {
                    val map = HashMap<String, Any>()
                    map.put("phoneNo", java.lang.Long.parseLong(password_phone!!.text.toString().trim { it <= ' ' }))
                    //检测账号是否可用
//                    if (name == "1") {//注册
                    var postMap: HashMap<String, Any> = HashMap()
                    getPostMap(this, USER_MSG_CODE, map, postMap)
                    checkcodeToken = postMap.get("token").toString()
                    OkHttpManager.postAsync(ANDROID_HTTP, "USER_MSG_CODE", postMap, this)
                    mCountDownTimerUtils = CountDownTimerUtils(password_button_code, (60 * 1000).toLong(), 1000)
                    mCountDownTimerUtils!!.start()
                }
            }
            R.id.password_button_confirm -> {

                //注册修改功能
                if (TextUtils.isEmpty(password_phone!!.text.toString() + "")) {
                    this.showShortToast("您输入的手机号码不能为空")
                } else if (!StringUtil.isMobileNO(password_phone!!.text.toString() + "")) {
                    this.showShortToast("您输入的手机号码不正确,请重新输入")
                    password_phone!!.setText("")
                } else {

                    val map = HashMap<String, Any>()
                    map.put(getString(R.string.phoneNo), password_phone!!.text.toString() + "")//手机号
                    map.put(getString(R.string.source), CODE_FROM)//客户端APP

                    if (name == "1") {//注册
                        if (TextUtils.isEmpty(password_edittext_code!!.text.toString() + "")) {
                            this.showShortToast("请输入验证码")
                        } else if (TextUtils.isEmpty(password_edittext_pass!!.text.toString() + "") ||
                                TextUtils.isEmpty(password_edittext_pass_confirm!!.text.toString() + "")) {
                            this.showShortToast( "密码不能为空")

                        } else if (password_edittext_pass_confirm?.text?.length!! < 6 || password_edittext_pass?.text?.length!! < 6) {
                            this.showShortToast( "长度不能小于6位！")
                            password_edittext_pass?.setText("")
                            password_edittext_pass_confirm?.setText("")
                        } else if ((password_edittext_pass!!.text.toString() + "").equals(
                                        password_edittext_pass_confirm!!.text.toString() + "")) {

                            map.put(getString(R.string.channelNo), AppUtil.getInstance().getChannel(this@SetUpPasswordActivity, 2))//渠道号
                            map.put(getString(R.string.msgCode), password_edittext_code!!.text.toString() + "")//验证码
                            map.put(getString(R.string.password), StringUtil.getMD5String(password_edittext_pass_confirm?.text.toString()))//密码
                            var postMap: HashMap<String, Any> = HashMap()
                            getPostMap(this, USER_REGISTER, map, postMap)
                            registerToken = postMap.get("token").toString();
                            OkHttpManager.postAsync(ANDROID_HTTP, "REGISTER_FILDER", postMap, this)
                        } else {
                            this.showShortToast( "两次密码不相同！")
                            password_edittext_pass?.setText("")
                            password_edittext_pass_confirm?.setText("")
                        }

                    } else {
                        //忘记密码
                        if (passwordType == 2) {//忘记密码
                            if (TextUtils.isEmpty(password_edittext_code!!.text.toString() + "")) {
                                this.showShortToast("请输入验证码")
                            } else if (TextUtils.isEmpty(password_edittext_pass!!.text.toString() + "") ||
                                    TextUtils.isEmpty(password_edittext_pass_confirm!!.text.toString() + "")) {
                                this.showShortToast( "密码不能为空")

                            } else if (password_edittext_pass_confirm?.text?.length!! < 6 || password_edittext_pass?.text?.length!! < 6) {
                                this.showShortToast( "长度不能小于6位！")
                                password_edittext_pass?.setText("")
                                password_edittext_pass_confirm?.setText("")
                            } else if ((password_edittext_pass!!.text.toString() + "").equals(
                                            password_edittext_pass_confirm!!.text.toString() + "")) {

                                var passWords: String? = password_edittext_pass_confirm!!.text.toString() + ""
                                passWords = StringUtil.getMD5String(passWords)
                                map.put(getString(R.string.password), passWords!!)
                                map.put(getString(R.string.msgCode), password_edittext_code?.text.toString())//短信验证码
                                map.put("type", passwordType)
                                var postMap: HashMap<String, Any> = HashMap()
                                getPostMap(this, USER_PASSWORD, map, postMap)
                                registerToken = postMap.get("token").toString()
                                OkHttpManager.postAsync(ANDROID_HTTP, "PASSWORD_REPAIR", postMap, this)
                            } else {
                                this.showShortToast( "两次密码不相同！")
                                password_edittext_pass?.setText("")
                                password_edittext_pass_confirm?.setText("")
                            }
                        } else if (passwordType == 1) {
                            if (password_edittext_pass_confirm?.text?.length!! < 6 || password_edittext_pass?.text?.length!! < 6) {
                                this.showShortToast( "长度不能小于6位！")
                                password_edittext_pass?.setText("")
                                password_edittext_pass_confirm?.setText("")
                            }else {
                                //修改密码
                                var map = HashMap<String, Any>()
                                map.put(getString(R.string.userNo), SharedPreferencesUtils.get(this, getString(R.string.userNo), "").toString())//用户id
                                map.put(getString(R.string.phoneNo), SharedPreferencesUtils.get(this, getString(R.string.phoneNo), "").toString())//手机号
                                map.put(getString(R.string.oldPassword), StringUtil.getMD5String(password_edittext_pass?.text.toString()))//旧密码
                                map.put(getString(R.string.password), StringUtil.getMD5String(password_edittext_pass_confirm?.text.toString()))//新密码
                                map.put(getString(R.string.msgCode), password_edittext_code?.text.toString())//短信验证码
                                map.put("type", passwordType)//修改密码类型

                                var postMap = HashMap<String, Any>()
                                getPostMap(this, USER_PASSWORD, map, postMap, SharedPreferencesUtils.get(this, getString(R.string.token), "").toString())
                                OkHttpManager.postAsync(ANDROID_HTTP, "PASSWORD_RENAME", postMap, this)
                            }
                        } else {
                        }

                    }
                }
            }
        }

    }

    override fun findViewById() {
        findViewById<View>(title_image).visibility = View.VISIBLE
        findViewById<View>(title_image).setOnClickListener(this)
        val title_view = findViewById<TextView>(title_view)
        password_button_code!!.setOnClickListener(this)
        password_button_confirm!!.setOnClickListener(this)
        if (name == "1") {
            title_view.text = this.getString(R.string.name_loan_logo_register)
            password_button_confirm!!.text = this.getString(R.string.name_loan_logo_register)
            agreement_password.visibility = View.VISIBLE
            act_log_register_agreement.setOnClickListener {
                var intent = Intent(this,X5WebViewActivity::class.java)
                intent.putExtra("url", APP_AGREEMENT)
                this.startActivity(intent)
            }

        } else {

            if (passwordType == 2) {
                //忘记密码
                title_view.text = this.getString(R.string.name_loan_logo_no_password)
                password_button_confirm!!.text = this.getString(R.string.name_loan_personal_data_complete)
                agreement_password.visibility = View.GONE
                password_edittext_pass_linear.visibility = View.VISIBLE
                password_edittext_pass_confirm_linear.visibility = View.VISIBLE

            } else {
                //修改密码
                password_phone.isEnabled = false
                if (!USER_PhoneNo.isNullOrEmpty()){
                    password_phone.setText(USER_PhoneNo)
                }else{
                    newIntent<LogoActivity>()
                    finish()
                }
                act_set_up_password_code.visibility = View.GONE//验证码隐藏
                act_set_up_password_line.visibility = View.GONE
                title_view.text = this.getString(R.string.name_loan_set_up_password)
                password_button_confirm!!.text = this.getString(R.string.name_loan_personal_data_complete)
                agreement_password.visibility = View.GONE
                password_edittext_pass_linear.visibility = View.VISIBLE
                password_edittext_pass_confirm_linear.visibility = View.VISIBLE
                act_set_up_password_old.text = "旧密码"
                act_set_up_password_new.text = "新密码"
            }
        }
    }

    override fun initView() {

    }

    override fun requestFailure(request: Request, name: String, e: IOException) {
        when (name) {
            "USER_MSG_CODE" -> this.showShortToast(this.getString(R.string.network_timed))
            "PASSWORD_REPAIR" -> this.showShortToast(this.getString(R.string.network_timed))
            "PASSWORD_RENAME" -> this.showShortToast(this.getString(R.string.network_timed))
            "REGISTER_FILDER" -> this.showShortToast(this.getString(R.string.network_timed))
        }
    }

    override fun requestSuccess(result: String, name: String) {
        var objects: JSONObject? = null
        var code: String? = null
        when (name) {
            "USER_MSG_CODE" -> {
                objects = JSONObject(result)
                //验证码
                if (result.contains("reqData")) {
                    var data = objects.get("reqData").toString()
                    var key = checkcodeToken.substring(16, 32)
                    var keydCode = AESUtils.decrypt(key, data)//解密
                    objects = JSONObject(keydCode)
                    if (objects.get("code").equals("200")) {
                        //验证码发送成功
                        this.showShortToast( "验证码发送成功！")
                    } else {
                        this.showShortToast( objects.get("msg").toString())
                    }
                }
            }
            "PASSWORD_REPAIR" -> {
                objects = JSONObject(result)
                //忘记密码
                if (result.contains("reqData")) {
                    var data = objects.get("reqData").toString()
                    var key = registerToken.substring(16, 32)
                    var keydCode = AESUtils.decrypt(key, data)//解密
                    objects = JSONObject(keydCode)
                    if (objects.get("code").equals("200")) {
                        this.showShortToast( "密码设置成功！")
                        USER_PhoneNo = password_phone.text.toString()
                        finish()//关闭当前界面
                    } else {
                        this.showShortToast( objects.get("msg").toString())
                    }
                }
            }

            "PASSWORD_RENAME" -> {
                objects = JSONObject(result)
                //修改密码
                if (result.contains("reqData")) {
                    var data = objects.get("reqData").toString()
                    var key = SharedPreferencesUtils.get(this, getString(R.string.token), "").toString().substring(16, 32)
                    var keydCode = AESUtils.decrypt(key, data)//解密
                    objects = JSONObject(keydCode)
                    if (objects.get("code").equals("200")) {
                        //修改成功
                        this.showShortToast( "密码修改成功！")
                        USER_PhoneNo = password_phone.text.toString()
                        SharedPreferencesUtils.clear(this)
                        newIntent<LogoActivity>()
                        finish()//关闭当前界面
                    } else {
                        this.showShortToast( objects.get("msg").toString())
                    }
                }

            }
            "REGISTER_FILDER" -> {

                objects = JSONObject(result)
                if (result.contains("reqData")) {
                    var data = objects.get("reqData").toString()
                    var key = registerToken.substring(16, 32)
                    var keydCode = AESUtils.decrypt(key, data)//解密
                    objects = JSONObject(keydCode)
                    if (objects.get("code").equals("200")) {
                        //注册成功
                        this.showShortToast( "注册成功！")
                        USER_PhoneNo = password_phone.text.toString()
                        SharedPreferencesUtils.clear(this)
                        finish()//关闭当前界面
                    } else {
                        this.showShortToast( objects.get("msg").toString())
                    }
                }

            }
        }
    }


    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        KeyBoardUtils.closeKeyboard(this, password_edittext_pass_confirm!!)
        MobclickAgent.onPause(this)
    }


}
